package com.example.administrator.text.Framgnet;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.administrator.text.R;
import com.google.gson.Gson;

import org.apache.log4j.Logger;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.Gridadapter;
import adapter.RecyclerHome;
import adapter.WelfareHeadAdapter;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import data.SharedPreferencesUtils;
import entity.HomeZhuYe;
import util.BitmapUtil;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.listComparator.HomeZhuYeButonn;
import util.listComparator.HomeZhuYeButonnImage;
import util.listComparator.HomeZhuYeHeadImage;
import util.listComparator.HomeZhuYeHeadText;
import util.listComparator.HomeZhuYeMiddle;
import view.GrapeGridview;
import view.HeadGallery;
import view.diaLogView.CrowdRetunDialog;
import view.diaLogView.UploadDialog;

/**
 *福利页的相关信息
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class WelfareFragment extends Fragment{
    private View mView;
    private UploadDialog mUploadDialog;
    private HashMap<String,Object> mMap;
    private Logger mLogger = Logger.getLogger(HomeFragment.class);
    private WelfareHeadAdapter mWelfareHeadAdapter;
    private FragmentManager mFragmentManager;
    private RecyclerHome mRecyclerHome;
    private Gridadapter mGridadapter,mGridavdapterIv;
    private List<HomeZhuYe.BannerModelsBean.TextModelsBean> mTextModels; //头部侧滑文字
    private List<HomeZhuYe.BannerModelsBean.PicModelsBean> mPicModels;  //头部侧滑的图片
    private List<HomeZhuYe.FeatureModelsBean> mFetureModelsBean;       //中间的图标数据
    private List<HomeZhuYe.HotSiteModelsBean> mHotSitModelsBean;      //底部的图标数据
    private List<HomeZhuYe.AdModelsBean> mAdModelsBean;              //底部的图片

    @Bind(R.id.fragment_welfare_head)             HeadGallery mHeadGallery;
    @Bind(R.id.fragment_welfare_fail)             ImageView mIVFail;
    @Bind(R.id.fragment_welfare_middle1_rv)       RecyclerView mRVmiddle1;         //中间的视图
    @Bind(R.id.fragment_welfare_button_gd)        GrapeGridview mGDButton;        //底部Gridview
    @Bind(R.id.fragment_welfare_button_imageview) GrapeGridview mGDImageView;    //底部imageView
    @Bind(R.id.fragment_welfare_linear1)          LinearLayout mLinearLayout1;
    @Bind(R.id.fragment_welfare_linear2)          LinearLayout mLinearLayout2;

    public WelfareFragment() {

    }

    public static WelfareFragment newInstance() {

        return new WelfareFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_welfare, container, false);
        ButterKnife.bind(this, mView);
        return mView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * 加载数据
     */
    private void initData() {
        if(mUploadDialog == null){
            mUploadDialog = new UploadDialog(getActivity(),"加载中");
            mUploadDialog.show();
        }else {
            mUploadDialog.show();
        }
        mMap = new HashMap<>();
        String id = (String) SharedPreferencesUtils.getParam(getActivity(), HomeUtil.mUseridDB,"");
        String token = (String) SharedPreferencesUtils.getParam(getActivity(), HomeUtil.mTokenDB,"");
        mMap.put("userid",id);
        mMap.put("token", token);
        mMap.put("areaid", MyApplication.getApp().getSiteAreaid());
        if(getString(R.string.app_name).equals("牛欢WiFi")){
            mMap.put("appType",2);
        }else if(getString(R.string.app_name).equals("NewFi")){
            mMap.put("appType",1);
        }
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngUrl_pageHome,stringJson,token,id,time);
        Map map = StringUtil.getStringUtilNew().getMapNew(getActivity(),stringJson,token,id,Url.mStirngUrl_pageHome,stirngSign,time);
        mLogger.info("initData（）-->加载数据--fwq"+MyApplication.getApp().getFWQString()+"stringJson"+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(getActivity(),MyApplication.getApp().getFWQString(),1,map,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                Gson gson = new Gson();
                LogUtil.eE("",response);
                mIVFail.setVisibility(View.GONE);
                mUploadDialog.dismiss();
                HomeZhuYe homezhuye = gson.fromJson(response,HomeZhuYe.class);
                if(homezhuye.getCode() == 1){
                    mTextModels = homezhuye.getBannerModels().getTextModels();
                    mPicModels = homezhuye.getBannerModels().getPicModels();
                    mFetureModelsBean = homezhuye.getFeatureModels();
                    mHotSitModelsBean = homezhuye.getHotSiteModels();
                    mAdModelsBean = homezhuye.getAdModels();

                    Collections.sort(mTextModels,new HomeZhuYeHeadText());
                    Collections.sort(mPicModels,new HomeZhuYeHeadImage());
                    Collections.sort(mFetureModelsBean,new HomeZhuYeMiddle());
                    Collections.sort(mHotSitModelsBean,new HomeZhuYeButonn());
                    Collections.sort(mAdModelsBean,new HomeZhuYeButonnImage());

                    setHeadView();
                    initViewPagerMiddle1();
                }else if(homezhuye.getCode() == -1){
                    mUploadDialog.dismiss();
                    Toast.makeText(getActivity(),getString(R.string.FWQ), Toast.LENGTH_SHORT).show();
                }else if(homezhuye.getCode() == -2){
                    mUploadDialog.dismiss();
                    CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(getActivity());
                    crowdRetunDialog.show();
                }else {
                    mUploadDialog.dismiss();
                }
            }

            @Override public void onFailure(Throwable error) {
                mIVFail.setVisibility(View.VISIBLE);
                mUploadDialog.dismiss();
                mIVFail.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initData();
                    }
                });
                StringUtil.getStringUtilNew().getExceptionCode(getActivity(), error.toString());
            }
        });
    }

    /**
     * fragmentManager
     */
    public void getFManager(FragmentManager fragmentManager){
        this.mFragmentManager = fragmentManager;
    }

    /**
     * 加载头部View
     *
     */
    private void setHeadView(){
        BitmapUtil.newBitmap().getListBimap(mPicModels, new BitmapUtil.OnBitmapClickListenerList() {
            @Override
            public void onBitmapClick(List<Bitmap> list) {
                LogUtil.eE("",list.size()+"");
                mWelfareHeadAdapter = new WelfareHeadAdapter (getActivity(),list);
                mHeadGallery.setAdapter(mWelfareHeadAdapter);
                mHeadGallery.setFocusable(true);
            }
        });

    }

    /**
     * 中间的ViewPager
     */
    public void initViewPagerMiddle1(){
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),4);
        mRVmiddle1.setLayoutManager(gridLayoutManager);
        mRecyclerHome = new RecyclerHome(getActivity(), mFetureModelsBean,null,null,3);
        //mRecyclerHome.getItemViewType(1);
        //SpaceItemDecoration spaceItemDecoration = new SpaceItemDecoration(getActivity(),1,mRecyclerHome);
        mRVmiddle1.setAdapter(mRecyclerHome);

        mGridadapter = new Gridadapter(getActivity(),mHotSitModelsBean,null,1);
        mGDButton.setAdapter(mGridadapter);

        if(mAdModelsBean.size() == 1){
            mGDImageView.setNumColumns(1);
        }else if(mAdModelsBean.size() == 0){
            mLinearLayout1.setVisibility(View.GONE);
            mLinearLayout2.setVisibility(View.GONE);
        }else {
            mGDImageView.setNumColumns(2);
        }

        mGridavdapterIv = new Gridadapter(getActivity(),null,mAdModelsBean,2);
        mGDImageView.setAdapter(mGridavdapterIv);
    }

}
